package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.feign.BehaviorEntryFeign;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.ApCollectionService;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings("ALL")
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {
    @Autowired
    private BehaviorEntryFeign behaviorEntryFeign;

    /**
     * 收藏
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collections(CollectionBehaviorDto dto) {
        //1、检查参数
        if (dto == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数为空");
        }
        //获取user对象
        ApUser user = AppThreadLocalUtils.getUser();
        //获取实体对象
        ApBehaviorEntry apBehaviorEntry = behaviorEntryFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"对象为空");
        }
        //进行收藏操作
        ApCollection apCollection=getOne(Wrappers.<ApCollection>lambdaQuery()
                                    .eq(ApCollection::getEntryId,apBehaviorEntry.getId())
                                    .eq(ApCollection::getArticleId,dto.getArticleId()));
        if (apCollection==null){
            //添加收藏信息
            ApCollection ac = new ApCollection();
            ac.setEntryId(apBehaviorEntry.getId());
            ac.setArticleId(dto.getArticleId());
            ac.setCollectionTime(new Date());
            ac.setType(dto.getType());
            ac.setPublishedTime(dto.getPublishedTime());
            save(ac);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            //修改
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            updateById(apCollection);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
